
import { type PaginationProps } from "@pureadmin/table";
import { ElMessage, FormInstance } from "element-plus";
import { ref, reactive, watch, onMounted } from "vue";
import {
  BuildRiskControlModelBaseData, RiskControlStrategyModelList, BuildRiskControlStrategyModel,
  RiskControlStrategyModelDetail
} from "@/api/stu/bankBigData";
import { useRoute } from "vue-router";
import qs from "qs";
import { log } from "console";
export function useRiskStrategic() {
  const route = useRoute();
  const dataList = ref<any>([]);
  const loading = ref<boolean>(true);
  const CreditVisible = ref<boolean>(false);
  const showVisible = ref<boolean>(false);
  const detailVisible = ref<boolean>(false);
  const regex = /^[\u4e00-\u9fa5]{1,20}$/;// 校验2-4个字中文
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    pageSizes: [10, 20, 50, 100],
    background: true
  });
  const formData = reactive({
    modelName: '',
    customerType: '',
    //评级集合
  })

  const companyList = reactive({
    financialIndicatorsList: [],//企业重大负面舆情
    competitiveIndicatorsList: [

    ],//外部评级下降
    creditIndicatorsList: [

    ]//财务指标恶化
  })

  const showType = ref()
  const showTittle = ref()
  const showList = ref()
  //公司客户选项数据
  const operationListSelect = reactive([
    {
      "selectId": ">",
      "selectName": ">",
      "selectContent": ">"
    },
    {
      "selectId": "=",
      "selectName": "=",
      "selectContent": "="
    },
    {
      "selectId": "<",
      "selectName": "<",
      "selectContent": "<"
    },
    {
      "selectId": ">=",
      "selectName": ">=",
      "selectContent": ">="
    },
    {
      "selectId": "<=",
      "selectName": "<=",
      "selectContent": "<="
    },
    {
      "selectId": "≠",
      "selectName": "≠",
      "selectContent": "≠"
    },
  ])

  const operationListInput = reactive([
    {
      "selectId": "包含",
      "selectName": "包含",
      "selectContent": "包含"
    },
    {
      "selectId": "不包含",
      "selectName": "不包含",
      "selectContent": "不包含"
    }
  ])

  const companySelectData = reactive({
    responsesStrategysList: [], //策略列表
    CompanyNegativePublicOpinionSelectList: [], //企业重大负面舆情
    ExternalRatingDowngradeSelectList: [], //外部评级下降
    DeteriorationFinancialIndicatorsSelectList: [] //财务指标恶化
  })
  //零售客户选项数据
  const retailList = reactive({
    financialIndicatorsList: [],//
  })
  const companyFilterData = ref([])
  const retailSelectData = reactive({
    responsesStrategysList: [],
    CompanyNegativePublicOpinionSelectList: [],
  })


  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      width: 120
    },
    {
      label: "模型名称",
      prop: "policyName",
      minWidth: 200
    },
    {
      label: "客户群名称",
      prop: "customerType",
      minWidth: 100
    },
    {
      label: "操作",
      fixed: "right",
      width: 200,
      slot: "operation"
    }
  ];

  const BtnLoading = ref<boolean>(false)
  function OUTBtnLoding() {
    setTimeout(() => {
      BtnLoading.value = false
    }, 1000)
  }

  function ApplyCreditScore() {
    CreditVisible.value = true;
  }
  //置空表单
  function CloseVisible() {
    CreditVisible.value = false;
    formData.customerType = ''
    formData.modelName = ''
    companyList.competitiveIndicatorsList = []
    companyList.creditIndicatorsList = []
    companyList.financialIndicatorsList = []
    retailList.financialIndicatorsList = []
    companyFilterData.value = []
  };



  // 确定
  async function SubmitVisible() {
    if (regex.test(formData.modelName) === false) {
      ElMessage.warning('策略名称应输入1-20个汉字')
      return
    }
    const data = {
      planId: route.query.planId,
      taskId: route.query.taskId,
      customerType: 'CompanyCustomers',
      policyName: formData.modelName,
    }
    if (formData.customerType === 'CompanyCustomers') {
      const riskSignals = [];
      companyList.financialIndicatorsList.forEach(item => {
        const arr = []
        item.indexInfos.forEach(item => {
          arr.push({
            operatorStr: item.confirmSelect,
            fieldName: item.dataField,
            parameterValue: item.confirmSelectValue,
            remark: item.remark
          })
        })
        riskSignals.push({
          moduleCode: item.moduleCode,
          modelCode: item.modelCode,
          responsesStrategy: item.responsesStrategy,
          indexInfos: arr,
        })
      })
      companyList.competitiveIndicatorsList.forEach(item => {
        const arr = []
        item.indexInfos.forEach(item => {
          arr.push({
            operatorStr: item.confirmSelect,
            fieldName: item.dataField,
            parameterValue: item.confirmSelectValue,
            remark: item.remark
          })
        })
        riskSignals.push({
          moduleCode: item.moduleCode,
          modelCode: item.modelCode,
          responsesStrategy: item.responsesStrategy,
          indexInfos: arr,
        })
      })
      companyList.creditIndicatorsList.forEach(item => {
        const arr = []
        item.indexInfos.forEach(item => {
          arr.push({
            operatorStr: item.confirmSelect,
            fieldName: item.dataField,
            parameterValue: item.confirmSelectValue,
            remark: item.remark
          })
        })
        riskSignals.push({
          moduleCode: item.moduleCode,
          modelCode: item.modelCode,
          responsesStrategy: item.responsesStrategy,
          indexInfos: arr,
        })
      })
      data.riskSignals = riskSignals;
      data.studentAnswer = JSON.stringify(data);
      console.log(data);
    } else {
      const riskSignals = [];
      data.customerType = 'RetailCustomers'
      retailList.financialIndicatorsList.forEach(item => {
        const arr = []
        item.indexInfos.forEach(item => {
          arr.push({
            operatorStr: item.confirmSelect,
            fieldName: item.dataField,
            parameterValue: item.confirmSelectValue,
            remark: item.remark
          })
        })
        riskSignals.push({
          moduleCode: item.moduleCode,
          modelCode: item.modelCode,
          responsesStrategy: item.responsesStrategy,
          indexInfos: arr,
        })
      })
      data.riskSignals = riskSignals;
      data.studentAnswer = JSON.stringify(data);
      console.log(data);
    }
    BtnLoading.value = true;
    OUTBtnLoding()
    const res = await BuildRiskControlStrategyModel(data);
    if (res.success) {
      ElMessage.success(res.msg)
      CloseVisible()
      getList()
    } else {
      ElMessage.error(res.msg)
    }
  }

  function handleSizeChange() {
    getList()
  }

  function handleCurrentChange() {
    getList()
  }


  async function getList() {
    const data = {
      pageIndex: pagination.currentPage,
      pageCount: pagination.pageSize,
      planId: route.query.planId,
      taskId: route.query.taskId,
    }
    const res = await RiskControlStrategyModelList(data);
    if (res.success) {
      res.data?.items.forEach(item => {
        item.createTime = item.createTime.substring(0, 10)
      })
      pagination.total = res.data.totalCount;
      dataList.value = res.data.items;
      loading.value = false;
    } else {
      ElMessage.error(res.msg);
      setTimeout(() => {
        loading.value = false;
      }, 1500)
    }
  }
  //添加企业重大负面舆情
  function changeSelectCompanyFinan(t, item) {
    for (let i = 0; i < item.length; i++) {
      if (item[i].apiFieldInfoId == t.apiFieldInfoId) {
        item.splice(i, 1); // 删除已有项
        return;
      }
    }
    item.push({
      modelCode: "CompanyNegativePublicOpinion",
      apiFieldInfoId: t.apiFieldInfoId,
      dataField: t.dataField,
      remark: t.remark,
      selection: t.selectOption,
      filedType: t.fieldType,
      confirmSelect: '',
      confirmSelectValue: ''
    })
  }

  //添加企业重大负面舆情
  function addCompanyNegativePublicOpinion() {
    companyFilterData.value.push({ modelCode: "CompanyNegativePublicOpinion", type: 1 })
    if (companyList.financialIndicatorsList.length == 5) {
      ElMessage.warning('最多只能创建五个企业重大负面舆情指标')
      return
    }
    companyList.financialIndicatorsList.push({
      moduleCode: "CompanyRiskControl",
      modelCode: "CompanyNegativePublicOpinion",
      responsesStrategy: '',
      finanItems: [],
      indexInfos: [],
    })
  }
  //
  function changeSelectCompanyFinan1(t, item) {
    for (let i = 0; i < item.length; i++) {
      if (item[i].apiFieldInfoId == t.apiFieldInfoId) {
        item.splice(i, 1); // 删除已有项
        return;
      }
    }
    item.push({
      modelCode: "ExternalRatingDowngrade",
      apiFieldInfoId: t.apiFieldInfoId,
      dataField: t.dataField,
      remark: t.remark,
      selection: t.selectOption,
      filedType: t.fieldType,
      confirmSelect: '',
      confirmSelectValue: ''
    })
  }

  function addExternalRatingDowngrade() {
    companyFilterData.value.push({ modelCode: "CompanyNegativePublicOpinion", type: 2 })
    if (companyList.competitiveIndicatorsList.length == 5) {
      ElMessage.warning('最多只能创建五个外部评级下降指标')
      return
    }
    companyList.competitiveIndicatorsList.push({
      moduleCode: "CompanyRiskControl",
      modelCode: "ExternalRatingDowngrade",
      responsesStrategy: '',
      finanItems: [],
      indexInfos: [],
    })
  }
  //添加公司客户信用指标
  function changeSelectCompanyFinan2(t, item) {
    for (let i = 0; i < item.length; i++) {
      if (item[i].apiFieldInfoId == t.apiFieldInfoId) {
        item.splice(i, 1); // 删除已有项
        return;
      }
    }
    item.push({
      modelCode: "DeteriorationFinancialIndicators",
      apiFieldInfoId: t.apiFieldInfoId,
      dataField: t.dataField,
      remark: t.remark,
      selection: t.selectOption,
      filedType: t.fieldType,
      confirmSelect: '',
      confirmSelectValue: ''
    })
  }

  function addDeteriorationFinancialIndicators() {
    companyFilterData.value.push({ modelCode: "CompanyNegativePublicOpinion", type: 3 })
    if (companyList.creditIndicatorsList.length == 5) {
      ElMessage.warning('最多只能创建五个财务指标恶化')
      return
    }
    companyList.creditIndicatorsList.push({
      moduleCode: "CompanyRiskControl",
      modelCode: "DeteriorationFinancialIndicators",
      responsesStrategy: '',
      finanItems: [],
      indexInfos: [],
    })
  }

  //添加零售客户
  function changeSelectCompanyFinan3(t, item) {
    for (let i = 0; i < item.length; i++) {
      if (item[i].apiFieldInfoId == t.apiFieldInfoId) {
        item.splice(i, 1); // 删除已有项
        return;
      }
    }
    item.push({
      modelCode: "PersonalCreditOverdue",
      apiFieldInfoId: t.apiFieldInfoId,
      dataField: t.dataField,
      remark: t.remark,
      selection: t.selectOption,
      filedType: t.fieldType,
      confirmSelect: '',
      confirmSelectValue: ''
    })
  }

  function addPersonalCreditOverdue() {
    if (retailList.financialIndicatorsList.length == 5) {
      ElMessage.warning('最多只能创建五个个人征信恶化指标')
      return
    }
    retailList.financialIndicatorsList.push({
      moduleCode: "RatingRiskControl",
      modelCode: "PersonalCreditOverdue",
      responsesStrategy: '',
      finanItems: [],
      indexInfos: [],
    })
  }



  //处理新建模型数据
  async function handleCreatedModelData() {
    const data = {
      planId: route.query.planId,
      taskId: route.query.taskId,
    }
    let res = await BuildRiskControlModelBaseData(data)
    if (res.success) {
      companySelectData.responsesStrategysList = res?.data.companyData.responsesStrategys
      companySelectData.CompanyNegativePublicOpinionSelectList = res?.data.companyData.fieldInfoData.filter(item => item.modelCode == 'CompanyNegativePublicOpinion')[0]
      companySelectData.ExternalRatingDowngradeSelectList = res?.data.companyData.fieldInfoData.filter(item => item.modelCode == 'ExternalRatingDowngrade')[0]
      companySelectData.DeteriorationFinancialIndicatorsSelectList = res?.data.companyData.fieldInfoData.filter(item => item.modelCode == 'DeteriorationFinancialIndicators')[0]
      retailSelectData.responsesStrategysList = res?.data.retailData.responsesStrategys
      retailSelectData.CompanyNegativePublicOpinionSelectList = res?.data.retailData.fieldInfoData.filter(item => item.modelCode == 'PersonalCreditOverdue')[0]
    } else {
      ElMessage.error(res.msg);
    }
  }

  //展示详情
  async function ShowReportDestail(row) {
    const data = {
      planId: route.query.planId,
      taskId: route.query.taskId,
      detailId: row.riskControlStrategyModelId
    }
    let res = await RiskControlStrategyModelDetail(data)
    if (res.success) {
      showList.value = res?.data.riskSignals
      showTittle.value = res.data.policyName
      showType.value = res.data.customerType
      detailVisible.value = true
    } else {
      ElMessage.error(res.msg);
    }
  }

  function deleteCustomer() {
    if (retailList.financialIndicatorsList.length > 1) {
      retailList.financialIndicatorsList.pop()
    } else {
      ElMessage.warning('至少保留一个策略')
    }

  }
  function deleteCompany() {
    const filterItem = companyFilterData.value[companyFilterData.value.length - 1].type
    if (filterItem == 1) {
      if (companyFilterData.value.length > 1) {
        companyList.financialIndicatorsList.pop()
        companyFilterData.value.pop()
      } else {
        ElMessage.warning('至少保留一个策略')
      }
    }
    if (filterItem == 2) {
      if (companyFilterData.value.length > 1) {
        companyList.competitiveIndicatorsList.pop()
        companyFilterData.value.pop()

      } else {
        ElMessage.warning('至少保留一个策略')
      }
    }
    if (filterItem == 3) {
      if (companyFilterData.value.length > 1) {
        companyList.creditIndicatorsList.pop()
        companyFilterData.value.pop()

      } else {
        ElMessage.warning('至少保留一个策略')
      }
    }


  }
  onMounted(async () => {
    handleCreatedModelData()
    getList()
  })

  return {
    dataList,
    loading,
    CreditVisible,
    pagination,
    columns,
    formData,
    BtnLoading,
    handleCurrentChange,
    handleSizeChange,
    ApplyCreditScore,
    SubmitVisible,
    CloseVisible,
    companyList,
    retailList,
    companySelectData,
    retailSelectData,
    operationListInput,
    operationListSelect,
    changeSelectCompanyFinan,
    addCompanyNegativePublicOpinion,
    changeSelectCompanyFinan1,
    addExternalRatingDowngrade,
    changeSelectCompanyFinan2,
    addDeteriorationFinancialIndicators,
    changeSelectCompanyFinan3,
    addPersonalCreditOverdue,
    ShowReportDestail,
    showList,
    showType,
    showTittle,
    showVisible,
    detailVisible,
    deleteCustomer,
    deleteCompany,
  }
}
